<?php

namespace app\xiangji\services;




use app\common\facades\auth\Auth;
use app\common\models\User;
use app\common\models\UserLover;
use app\Request;
use app\xiangji\caches\ScoreRankCache;
use app\xiangji\exception\BadRequestException;
use Carbon\Carbon;

class LoveScoreRankService
{
    public function top100(Request $request)
    {
        // 获取分页数据
        $page = $request->get('page', 1);
        $limit = $request->get('limit', 10);
        $start = ($page - 1) * $limit;
        $stop = $page * $limit - 1;
        $ranks = ScoreRankCache::getScoreRank($start, $stop);
        $ids = explode('-', implode('-', $ranks));
        // 查询排行榜中所有的用户基础信息
        $users = User::whereIn('id', $ids)->with(['lover' => function($query){
            $query->field(['id', 'user_id','bless_num', 'bind_time']);
        }])->field(['id', 'nickName', 'gender', 'avatarUrl'])->select()->toArray();
        $world = [];
        $ranking = 1 + (($page-1) * $limit); // 排名
        // 世界排名组合数据
        foreach ($ranks as $rank){
            list($user_id, $lover_id) = explode('-', $rank);
            $world[$rank]['bind_id'] = $rank;       // 绑定关系标识
            $world[$rank]['rank'] = $ranking ++;    // 排名
            $world[$rank]['score'] = (int)ScoreRankCache::getScore($rank);  // 恩爱值
            foreach ($users as $k => $user){
                if ($user['id'] != $user_id && $user['id'] != $lover_id){
                    continue;
                }
                $world[$rank]['bless_num'] = $user['lover']['bless_num'];
                $world[$rank]['bind_days'] = Carbon::parse($user['lover']['bind_time'])->diffInDays(Carbon::now());
                unset($user['lover']);
                $world[$rank]['lovers'][] = array_merge($user, [
                    'score' => (int)ScoreRankCache::getUserScore($user['id'])
                ]);
                unset($users[$k]);
            }
        }
        return [
            'total' => ScoreRankCache::queryRankCount(),
            'per_page' => (int)$limit,
            'current_page' => (int)$page,
            'last_page' => ceil(ScoreRankCache::queryRankCount()/$limit),
            'data' => array_values($world)
        ];
    }

    /**
     * 个人排行
     * @return array
     */
    public function selfRank()
    {
        // 个人排名信息
        $user = Auth::guard('api')->user();

        $data = [
            'rank' => ScoreRankCache::queryRankByScore((int)ScoreRankCache::getUserScore($user->id)) + 1,
            'score' => (int)ScoreRankCache::getUserScore($user->id),
            'bless_num' => $user->lover->bless_num,
            'lovers' => [
                [
                    'id' => $user->id,
                    'nickName'  => $user->nickName,
                    'gender'    => $user->gender,
                    'avatarUrl' => $user->avatarUrl,
                    'score'     => (int)ScoreRankCache::getUserScore($user->id)
                ],

            ]
        ];
        $lover = UserService::getUserLover($user);
        if ($lover){
            $data['rank'] = ScoreRankCache::queryLoverRank(implodeUserId($user->id, $lover->id)) + 1;
            $data['score'] += (int)ScoreRankCache::getUserScore($lover->id);
            $data['lovers'][] = [
                'id' => $lover->id,
                'nickName'  => $lover->nickName,
                'gender'    => $lover->gender,
                'avatarUrl' => $lover->avatarUrl,
                'score'     => (int)ScoreRankCache::getUserScore($lover->id)
            ];
        }
        return $data;
    }

    public function sendBless(Request $request)
    {
        $user = Auth::guard('api')->user();
        $today = Carbon::today()->format('Y-m-d');
        if (ScoreRankCache::getBless($user->id) == $today){
            throw new BadRequestException('您今天已经发送过祝福啦！');
        }
        // 判断是否已经点过赞了
        $bind_id = $request->post('bind_id', '0-0');
        // 查看是否再排行榜内，不在不能点赞
        if (!ScoreRankCache::getScore($bind_id)){
            throw new BadRequestException('数据不在top100内');
        }
        $ids = explodeUserId($bind_id);
        $res = UserLover::whereIn('user_id', $ids)->inc('bless_num')->update() && true;
        ScoreRankCache::setBless($user->id, $today);
        return $res;
    }
}
